<?php
/**
 * @package		简易CMS
 * @subpackage	插件函数包
 * @version		$Id: option_block.php 23 2012-06-11 18:04:03Z htmambo@gmail.com $
 * @author		Hoping
 * @copyright	Copyright (C) 2010 Hoping Software Studio.
 */
if(!defined('IN_JYCMS')) {
	exit('Access Denied');
}

define('CURSCRIPT', 'block');
define('NOROBOT', TRUE);

class block_ctrl extends application {
	function __construct(){
		$this->block_ctrl();
	}

	function block_ctrl(){
		global $_G, $modsession;
		$this->allowaction = array(
			'blockdata', 'portalblock', 'index'
		);

		$this->cachelist = array('portalcategory');
		parent::__construct();
		$task = in_array($_GET['task'], array('index', 'block', 'portalblock', 'blockdata'))?$_GET['task']:'index';
		$_G['gp_task'] = $task;
			require_once libfile('class/panel');
			$modsession = new ControlPanel(PORTALCP_PANEL);
		require_once libfile('function/portal');

	}

	function onIndex(){
		global $_G, $category, $navtitle;
		global $modsession;

		include_once libfile('function/block');
		$oparr = array('block', 'data', 'style', 'itemdata', 'setting', 'remove', 'item', 'blockclass',
						'getblock', 'thumbsetting', 'push', 'recommend', 'verifydata', 'managedata',
						'saveblockclassname', 'saveblocktitle', 'convert');
		$op = in_array($_GET['op'], $oparr) ? $_GET['op'] : 'block';
		$allowmanage = 0;
		$block = array();
		$bid = !empty($_G['gp_bid']) ? intval($_G['gp_bid']) : 0;
		if($bid) {
			$block = DB::fetch_first("SELECT b.* FROM #__common_block b WHERE b.bid='$bid'");
			if(empty($block)) {
				showmessage('The specified module does not exist!');
			}
			$_G['block'][$bid] = $block;
			if(checkperm('allowdiy')) $allowmanage = 1;
		}

		$block['param'] = empty($block['param'])?array():unserialize($block['param']);
		if(empty($block['bid'])) {
			$bid = 0;
		}

		$_GET['classname'] = !empty($_GET['classname']) ? $_GET['classname'] : ($block ? $block['blockclass'] : 'html_html');
		$theclass = block_getclass($_GET['classname'], true);
		$theclass['script'] = isset($theclass['script']) ? $theclass['script'] : array();
		if(!empty($_GET['styleid']) && isset($theclass['style'][$_GET['styleid']])) {
			$thestyle = $theclass['style'][$_GET['styleid']];
		} elseif(isset($theclass['style'][$block['styleid']])) {
			$_GET['styleid'] = intval($block['styleid']);
			$thestyle = $theclass['style'][$_GET['styleid']];
		} else {
			$_GET['styleid'] = 0;
			$thestyle = (array)unserialize($block['blockstyle']);
		}
		$_GET['script'] = !empty($_GET['script']) && isset($theclass['script'][$_GET['script']])
				? $_GET['script']
				: (!empty($block['script']) ? $block['script'] : key($theclass['script']));

		$blocktype = (!empty($_GET['blocktype']) || !empty($block['blocktype'])) ? 1 : 0;
		$nocachetime = in_array($_GET['script'], array('blank', 'line', 'banner', 'vedio', 'google')) ? true : false;
		$is_htmlblock = ($_GET['classname'] == 'html_html') ? 1 : 0;
		$showhtmltip = false;
		if($op == 'data' && $is_htmlblock) {
			$op = 'block';
			$showhtmltip = true;
		}
		$is_recommendable = block_isrecommendable($block);

		if($op == 'block') {
			if($bid && !$allowmanage) {
				showmessage('You do not have permission to add or edit module!');
			}
			if(!$bid) {
				list($tpl, $id) = explode(':', $_GET['tpl']);
				if(!$_G['group']['allowdiy']) {
					showmessage('You do not have permission to add or edit module!');
				}
			}

			if(submitcheck('blocksubmit')) {
				$_POST['cachetime'] = intval($_POST['cachetime']) * 60;
				$_POST['styleid'] = intval($_POST['styleid']);
				$_POST['shownum'] = intval($_POST['shownum']);
				$_POST['picwidth'] = $_POST['picwidth'] ? intval($_POST['picwidth']) : 0;
				$_POST['picheight'] = $_POST['picheight'] ? intval($_POST['picheight']) : 0;
				$_POST['script'] = isset($theclass['script'][$_POST['script']]) ?
									$_POST['script'] : key($theclass['script']);
				$_POST['a_target'] = in_array($_POST['a_target'], array('blank', 'top', 'self')) ? $_POST['a_target'] : 'blank';
				$_POST['dateformat'] = in_array($_POST['dateformat'], array('Y-m-d', 'm-d', 'H:i', 'Y-m-d H:i')) ? $_POST['dateformat'] : 'Y-m-d';

				$_POST['shownum'] = $_POST['shownum'] > 0 ? $_POST['shownum'] : 10;
				$_POST['parameter']['items'] = $_POST['shownum'];
				$setarr = array(
					'name' => getstr($_POST['name'], 255, 1, 1, 0, 0),
					'summary' => getstr($_POST['summary'], '', 1, 1, 0, 1),
					'styleid' => $_POST['styleid'],
					'script' => $_POST['script'],
					'param' => addslashes(serialize($_POST['parameter'])),
					'cachetime' => intval($_POST['cachetime']),
					'punctualupdate' => !empty($_POST['punctualupdate']) ? '1' : '0',
					'shownum' => $_POST['shownum'],
					'picwidth' => $_POST['picwidth'] && $_POST['picwidth'] > 8 && $_POST['picwidth'] < 1960 ? $_POST['picwidth'] : 0,
					'picheight' => $_POST['picheight'] && $_POST['picheight'] > 8 && $_POST['picheight'] < 1960 ? $_POST['picheight'] : 0,
					'target' => $_POST['a_target'],
					'dateuformat' => !empty($_POST['dateuformat']) ? '1' : '0',
					'dateformat' => $_POST['dateformat'],
					'hidedisplay' => $_POST['hidedisplay'] ? '1' : '0',
					'dateline' => TIMESTAMP
				);
				if($bid) {
					DB::update('common_block', $setarr, array('bid'=>$bid));
				} else {
					$setarr['blockclass'] = $_GET['classname'];
					$setarr['uid'] = $_G['uid'];
					$setarr['username'] = $_G['username'];
					$setarr['notinherited'] = 0;
					if($blocktype == 1) {
						$setarr['blocktype'] = '1';
					}
					$bid = DB::insert('common_block', $setarr, true);
				}
				$_G['block'][$bid] = DB::fetch_first("SELECT * FROM #__common_block WHERE bid='$bid'");
				block_updatecache($bid, true);
				showmessage('The operation completed!', 'index.php?option=block&op=block&bid='.$bid, array('bid'=>$bid, 'eleid'=> $_GET['eleid']));
			}

			loadcache('blockconvert');
			$block['script'] = isset($block['script']) ? $block['script'] : $_GET['script'];
			$settings = block_setting($_GET['classname'], $block['script'], $block['param']);
			$scriptarr = array($block['script'] => ' selected');
			$stylearr = array($_GET['styleid'] => ' selected');
			$block = block_checkdefault($block);
			$cachetimearr = array($block['cachetime'] =>' selected="selected"');
			$block['cachetime_min'] = intval($block['cachetime'] / 60);
			$targetarr[$block['target']] = ' selected';

			$dateformats = block_getdateformats($block['dateformat']);

			$block['summary'] = htmlspecialchars($block['summary']);
			$blockclassname = lang('blockclass', 'blockclass_'.($block['blockclass'] ? $block['blockclass'] : $_G['gp_classname']));

		} elseif($op == 'data') {
			if(!$bid || !$allowmanage) {
				showmessage('You do not have permission to add or edit module!');
			}

			if(submitcheck('updatesubmit')) {
				if(isset($_POST['bannedids']) && $block['param']['bannedids'] != $_POST['bannedids']) {
					$block['param']['bannedids'] = $_POST['bannedids'];
					DB::update('common_block', array('param'=>addslashes(serialize($block['param']))), array('bid'=>$bid));
					$_G['block'][$bid] = $block;
				}
				if($_POST['displayorder']) {
					asort($_POST['displayorder']);
					$orders = $ids = array();
					$order = 1;
					foreach((array)$_POST['displayorder'] as $k=>$v) {
						$k = intval($k);
						$ids[] = $k;
						$orders[$k] = $order;
						$order++;
					}
					$items = array();
					$query = DB::query("SELECT itemid, displayorder, itemtype FROM #__common_block_item WHERE bid='$bid' AND itemid IN (".dimplode($ids).')');
					while(($value=DB::fetch($query))) {
						$items[$value['itemid']] = $value;
					}
					foreach((array)$items as $key=>$value) {
						$itemtype = !empty($_POST['locked'][$key]) ? '1' : '2';
						if($orders[$key] != $value['displayorder'] || $itemtype != $value['itemtype']) {
							DB::update('common_block_item', array('displayorder'=>$orders[$key], 'itemtype'=>$itemtype), array('itemid'=>$key));
						}
					}
				}
				block_updatecache($bid, true);
				showmessage('The operation completed!', 'index.php?option=block&op=data&bid='.$bid, array('bid'=>$bid, 'eleid'=> $_GET['eleid']));
			}

			$itemlist = array();
			if($bid) {
				$query = DB::query("SELECT * FROM #__common_block_item WHERE bid='$bid' ORDER BY displayorder");
				$preorders = array();
				while(($value = DB::fetch($query))) {
					if($value['itemtype']==1 && $value['enddate'] && $value['enddate'] <= TIMESTAMP) {
						continue;
					}
					$value['ispreorder'] = false;
					if($value['itemtype']==1) {
						if($value['startdate'] > TIMESTAMP) {
							$value['ispreorder'] = true;
						} else {
							$preorders[$value['displayorder']] = $value['itemid'];
						}
					}
					$itemlist[$value['itemid']] = $value;
				}
				if($preorders) {
					foreach((array)$itemlist as $key=>$value) {
						if(isset($preorders[$value['displayorder']]) && $value['itemid'] != $preorders[$value['displayorder']]) {
							unset($itemlist[$key]);
						}
					}
				}
			}

			$block['param']['bannedids'] = !empty($block['param']['bannedids']) ? stripslashes($block['param']['bannedids']) : '';

		} elseif($op == 'style') {
			if(!$bid || !$allowmanage) {
				showmessage('You do not have permission to add or edit module!');
			}

			if(submitcheck('stylesubmit')) {
				$_POST['name'] = trim($_POST['name']);
				$arr = array(
					'name' => $_POST['name'],
					'blockclass' => $_GET['classname'],
				);
				$_POST['template'] = stripslashes($_POST['template']);

				include_once libfile('function/block');
				block_parse_template($_POST['template'], $arr);
				if(!empty($_POST['name'])) {
					$styleid = DB::insert('common_block_style', daddslashes($arr), true);
				}
				$arr['fields'] = unserialize($arr['fields']);
				$arr['template'] = unserialize($arr['template']);
				$arr = serialize($arr);
				$arr = addslashes($arr);
				DB::update('common_block', array('blockstyle'=>$arr, 'styleid'=>'0'), array('bid'=>$bid));

				showmessage('The operation completed!', 'index.php?option=block&op=style&bid='.$bid, array('bid'=>$bid, 'eleid'=> $_GET['eleid']));
			}

			$blockstyle = array();
			if(!empty($block['styleid'])) {
				$blockstyle = block_getstyle($block['styleid']);
			} else {
				$blockstyle = unserialize($block['blockstyle']);
			}
			$template = block_build_template($blockstyle['template']);

			$samplecode = '';
			if($block['hidedisplay']) {
				$samplecode = '<ul>\n'
					.'<!--{loop $_G[block_1] $key $value}-->\n'
					.'<li><a href="$value[url]">$value[title]</a></li>\n'
					.'<!--{/loop}-->\n'
					.'</ul>';
				$samplecode = htmlspecialchars($samplecode);
				$samplecode = str_replace('\n', '<br />', $samplecode);
			}

		} elseif($op == 'itemdata') {

			if(!$bid || !$allowmanage) {
				showmessage('You do not have permission to add or edit module!');
			}
			if(!$is_recommendable) {
				showmessage('This module does not contain recommendations Library!');
			}

			$theurl = 'index.php?option=block&op=itemdata';
			$perpage = 20;
			$page = max(1,intval($_GET['page']));
			$start = ($page-1)*$perpage;
			if($start<0) $start = 0;

			if(submitcheck('deletesubmit')) {
				$ids = array();
				if(!empty($_POST['ids'])) {
					$dataids = dimplode($_POST['ids']);
					$query = DB::query("SELECT dataid FROM #__common_block_item_data WHERE bid='$bid' AND dataid IN ($dataids)");
					while(($value=DB::fetch($query))) {
						$ids[] = intval($value['dataid']);
					}
				}
				if($ids) {
					DB::query("DELETE FROM #__common_block_item_data WHERE dataid IN (".dimplode($ids).")");
				}
				showmessage('The operation completed!', "index.php?option=block&op=itemdata&bid=$bid&page=$page");
			}

			$datalist = array();
			$query = DB::query("SELECT * FROM #__common_block_item_data WHERE bid='$bid' ORDER BY stickgrade DESC, verifiedtime DESC LIMIT $start, $perpage");
			while(($value=DB::fetch($query))) {
				$value['verifiedtime'] = dgmdate($value['verifiedtime']);
				$datalist[$value['dataid']] = $value;
			}

		} elseif($op == 'setting') {

			if(($bid && !$allowmanage)) {
				showmessage('You do not have permission to add or edit module!');
			}

			$settings = array();
			if($theclass['script'][$_GET['script']]) {
				$settings = block_setting($_GET['classname'], $_GET['script'], $block['param']);
			}
			$block['script'] = isset($block['script']) ? $block['script'] : $_GET['script'];
			$scriptarr = array($block['script'] => ' selected');
			$stylearr = array($_GET['styleid'] => ' selected');

			$block = block_checkdefault($block);
			$cachetimearr = array($block['cachetime'] =>' selected="selected"');
			$block['cachetime_min'] = intval($block['cachetime'] / 60);
			$targetarr[$block['target']] = ' selected';

		} elseif($op == 'thumbsetting') {

			if(($bid && !$allowmanage)) {
				showmessage('You do not have permission to add or edit module!');
			}

			$block = block_checkdefault($block);
			$cachetimearr = array($block['cachetime'] =>' selected="selected"');
			$block['cachetime_min'] = intval($block['cachetime'] / 60);
			$targetarr[$block['target']] = ' selected';

			$dateformats = block_getdateformats($block['dateformat']);

		} elseif($op == 'remove') {

			if(!$bid || !$allowmanage) {
				showmessage('You do not have permission to add or edit module!');
			}

			if($_GET['itemid']) {
				$_GET['itemid'] = intval($_GET['itemid']);
				$item = DB::fetch_first("SELECT * FROM #__common_block_item WHERE itemid='$_GET[itemid]' AND bid='$bid'");
				if($item) {
					DB::query("DELETE FROM #__common_block_item WHERE itemid='$_GET[itemid]'");
					if($item['itemtype'] != '1') {
						block_ban_item($block, $item);
					}
					block_updatecache($bid, true);
				}
			}
			showmessage('The operation completed!', "index.php?option=block&op=data&bid=$bid", array('bid'=>$bid));

		} elseif( in_array($op, array('item', 'push', 'recommend', 'verifydata', 'managedata'))) {

			if(!$bid) {
				showmessage('You do not have permission to add or edit module!');
			}

			$itemid = $_GET['itemid'] ? intval($_GET['itemid']) : 0;
			$dataid = $_GET['dataid'] ? intval($_GET['dataid']) : 0;
			$_GET['id'] = intval($_GET['id']);
			$_GET['idtype'] = preg_replace('/[^\w]/', '', $_GET['idtype']);

			$item = $perm = array();
			if($op == 'item') {
				if(!$allowmanage) {
					showmessage('You do not have permission to add or edit module!');
				}
				if($itemid) {
					$item = DB::fetch_first("SELECT * FROM #__common_block_item WHERE itemid='$itemid'");
					$item['fields'] = unserialize($item['fields']);
				}
			} elseif($op == 'push') {

				$item = get_push_item($thestyle, $_GET['id'], $_GET['idtype']);
				if($itemid) {
					$item['itemid'] = $itemid;
				}
			} elseif($op == 'recommend') {
				if(!checkperm('allowdiy')) {
					showmessage('You do not have permission recommendation data to the module!');
				}

				$isrepeatrecommend = false;
				$item = DB::fetch_first("SELECT * FROM #__common_block_item_data WHERE bid='$bid' AND id='$_GET[id]' AND idtype='$_GET[idtype]'");
				if($item) {
					$item['fields'] = unserialize($item['fields']);
					$isrepeatrecommend = true;

					if(!$perm['allowmanage'] && $item['uid'] != $_G['uid']) {
						showmessage('The data have been included in the module library of the recommended!');
					}

				} else {
					if(in_array($_GET['idtype'],array('tid', 'gtid', 'aid', 'picid', 'blogid'))) {
						$_GET['idtype'] = $_GET['idtype'].'s';
					}
					$item = get_push_item($thestyle, $_GET['id'], $_GET['idtype']);
				}
			} elseif($op=='verifydata' || $op=='managedata') {
				if(!checkperm('allowdiy')) {
					showmessage("You do not have permission to manage the module's recommendation data!");
				}
				if($dataid) {
					$item = DB::fetch_first("SELECT * FROM #__common_block_item_data WHERE dataid='$dataid'");
					$item['fields'] = unserialize($item['fields']);
				}
			}

			if(!$item) {
				showmessage('You do not have permission to add or edit module!');
			}

			if($item['picflag'] == '1') {
				$item['pic'] = $item['pic'] ? $_G['setting']['attachurl'].$item['pic'] : '';
			} elseif($item['picflag'] == '2') {
				$item['pic'] = $item['pic'] ? $_G['setting']['ftp']['attachurl'].$item['pic'] : '';
			}
			$item['picflag'] = '0';

			$item['startdate'] = $item['startdate'] ? dgmdate($item['startdate']) : dgmdate(TIMESTAMP);
			$item['enddate'] = $item['enddate'] ? dgmdate($item['enddate']) : '';
			$orders = range(1, $block['shownum']);
			$orderarr[$item['displayorder']] = ' selected="selected"';
			$item['showstyle'] = !empty($item['showstyle']) ? (array)(unserialize($item['showstyle'])) : array();
			$showstylearr = array();
			foreach(array('title_b', 'title_i', 'title_u', 'title_c', 'summary_b', 'summary_i', 'summary_u', 'title_c') as $value) {
				if(!empty($item['showstyle'][$value])) {
					$showstylearr[$value] = 'class="a"';
				}
			}

			$itemfields = $blockitem = $item;
			unset($itemfields['fields']);
			$item['fields'] = (array)$item['fields'];
			foreach((array)$item['fields'] as $key=>$value) {
				if($theclass['fields'][$key]) {
					switch($theclass['fields'][$key]['datatype']) {
						case 'date':
							$itemfields[$key] = dgmdate($value);
							break;
						case 'int':
							$itemfields[$key] = intval($value);
							break;
						case 'string':
							$itemfields[$key] = htmlspecialchars($value);
							break;
						default:
							$itemfields[$key] = $value;
					}
				}
			}

			$showfields = array();
			if(empty($thestyle['fields'])) {
				$template = block_build_template($thestyle['template']);
				$thestyle['fields'] = block_parse_fields($template);
				DB::update('common_block_style', array('fields'=>addslashes(serialize($thestyle['fields']))), array('styleid'=>intval($thestyle['styleid'])));
			}
			foreach((array)$thestyle['fields'] as $fieldname) {
				$showfields[$fieldname] = "1";
			}

			if(submitcheck('itemsubmit') || submitcheck('recommendsubmit') || submitcheck('verifydatasubmit') || submitcheck('managedatasubmit')) {
				$item['bid'] = $block['bid'];
				$item['displayorder'] = intval($_POST['displayorder']);
				$item['startdate'] = !empty($_POST['startdate']) ? strtotime($_POST['startdate']) : 0;
				$item['enddate'] = !empty($_POST['enddate']) ? strtotime($_POST['enddate']) : 0;
				$item['itemtype'] = !empty($_POST['locked']) ? '1' : '2';
				$item['title'] = htmlspecialchars($_POST['title']);
				$item['url'] = $_POST['url'];
				$item['summary'] = $_POST['summary'];
				if($_FILES['pic']['tmp_name']) {
					$result = pic_upload($_FILES['pic'], 'portal');
					$item['pic'] = 'portal/'.$result['pic'];
					$item['picflag'] = $result['remote'] ? '2' : '1';
					$item['makethumb'] = 0;
				} elseif($_POST['pic']) {
					$item['pic'] = $_POST['pic'];
					$item['picflag'] = intval($_POST['picflag']);
					$item['makethumb'] = 0;
				}
				$item['showstyle'] = $_POST['showstyle'] ? dstripslashes($_POST['showstyle']) : array();
				$item['showstyle'] = daddslashes(serialize($item['showstyle']));

				foreach((array)$theclass['fields'] as $key=>$value) {
					if(!isset($item[$key]) && isset($_POST[$key])) {
						if($value['datatype'] == 'int') {
							$_POST[$key] = intval($_POST[$key]);
						} elseif($value['datatype'] == 'date') {
							$_POST[$key] = strtotime($_POST[$key]);
						} else {
							$_POST[$key] = dstripslashes($_POST[$key]);
						}
						$item['fields'][$key] = $_POST[$key];
					}
				}
				$item['fields']	= addslashes(serialize($item['fields']));

				if(submitcheck('itemsubmit')) {

					if($item['startdate'] > $_G['timestamp']) {
						DB::insert('common_block_item', $item, false, true);
						if($block['itemtype']=='1') {
							block_ban_item($block, $item);
						}
					} elseif(empty($item['enddate']) || $item['enddate'] > $_G['timestamp']) {
						DB::query("DELETE FROM #__common_block_item WHERE bid='$bid' AND displayorder='$item[displayorder]'");
						DB::insert('common_block_item', $item, false, true);
						if($block['itemtype']=='1') {
							block_ban_item($block, $item);
						}
					} else {
						DB::query("DELETE FROM #__common_block_item WHERE itemid='$item[itemid]' AND bid='$bid'");
					}
					block_updatecache($bid, true);
					showmessage('The operation completed!', 'index.php?option=block&op=data&bid='.$block['bid'], array('bid'=>$bid));

				} elseif(submitcheck('recommendsubmit')) {
					unset($item['itemid']);
					$item['itemtype'] = '0';
					$item['uid'] = $_G['uid'];
					$item['username'] = $_G['username'];
					$item['dateline'] = TIMESTAMP;
					$item['isverified'] = empty($_POST['needverify']) && ($perm['allowmanage'] || empty($perm['needverify'])) ? '1' : '0';
					$item['verifiedtime'] = TIMESTAMP;

					DB::insert('common_block_item_data', $item, false, true);
					showmessage('The operation completed!', dreferer('index.php'), array(), array('showdialog' => true, 'closetime' => true));

				} elseif(submitcheck('verifydatasubmit')) {
					$item['isverified'] = '1';
					$item['verifiedtime'] = TIMESTAMP;
					DB::update('common_block_item_data', $item, array('dataid'=>$dataid));
					if(!empty($_POST['updateblock'])) {
						block_updatecache($bid, true);
					}
					showmessage('The operation completed!', dreferer('index.php?option=block&task=blockdata&op=manage&bid='.$bid));
				} elseif(submitcheck('managedatasubmit')) {
					$item['stickgrade'] = intval($_POST['stickgrade']);
					DB::update('common_block_item_data', $item, array('dataid'=>$dataid));
					showmessage('The operation completed!', dreferer('index.php?option=block&op=itemdata&bid='.$bid));
				}
			}

		} elseif ($op == 'getblock') {

			if(!$bid || !$allowmanage) {
				showmessage('You do not have permission to add or edit module!');
			}

			block_get_batch($bid);
			block_updatecache($bid, !empty($_GET['forceupdate']));
			if(strexists($block['summary'], '<script')) {
				$block['summary'] = lang('block', 'This module contains js code, not immediately preview, click Save to view');
				$_G['block'][$bid] = $block;
				$_G['block'][$bid]['cachetime'] = 0;
				$_G['block'][$bid]['nocache'] = true;
			}
			$html = block_fetch_content($bid, $block['blocktype']);

		} elseif ($op == 'saveblockclassname') {

			if(!$bid || !$allowmanage) {
				$this->ajaxReturn(0, $this->lang->_('You do not have permission to add or edit module!'));
			}

			if (submitcheck('saveclassnamesubmit')) {
				$setarr = array('classname'=>$_POST['classname']);
				DB::update('common_block',$setarr,array('bid'=>$bid));
			}
			$this->ajaxReturn(1, $this->lang->_('The operation completed!'));
		} elseif ($op == 'saveblocktitle') {

			if(!$bid || !$allowmanage) {
				$this->ajaxReturn(0, $this->lang->_('You do not have permission to add or edit module!'));
			}

			if (submitcheck('savetitlesubmit')) {
				$title = dstripslashes($_POST['title']);
				$title = preg_replace('/url\([\'"](.*?)[\'"]\)/','url($1)',$title);

				$_G['siteurl'] = str_replace(array('/','.'),array('\/','\.'),$_G['siteurl']);
				$title = preg_replace('/\"'.$_G['siteurl'].'(.*?)\"/','"$1"',$title);

				$setarr = array('title'=>daddslashes($title));
				DB::update('common_block',$setarr,array('bid'=>$bid));
			}
			$this->ajaxReturn(1, $this->lang->_('The operation completed!'));
		} elseif ($op == 'convert') {

			if(!$bid || !$allowmanage) {
				showmessage('You do not have permission to add or edit module!');
			}
			block_convert($bid, $_G['gp_toblockclass']);
		}

		include_once template("block/block");

	}

	function onPortalBlock(){
		global $modsession;
		global $_G, $category, $navtitle;
			if (getgpc('login_panel') && getgpc('cppwd') && submitcheck('submit')) {
				$modsession->dologin($_G[uid], getgpc('cppwd'), true);
			}

			if (!$modsession->islogin) {
				include template('portalcp/login');
				dexit();
			}

		$op = in_array($_GET['op'], array('recommend', 'search')) ? $_GET['op'] : 'getblocklist';

		if(!checkperm('allowdiy') && !checkperm('allowauthorizedblock')) {
			showmessage('You do not have permission to use the portal management', dreferer());
		}

		loadcache(array('diytemplatename'));
		loadcache('diytemplatename');
		$pageblocks = $tpls = $bids = $blocks = array();
		if(checkperm('allowdiy')) {
			$tpls = array_keys($_G['cache']['diytemplatename']);
		} else {
			$tpls = array();
		}
		if($tpls) {
			$query = DB::query("SELECT * FROM #__common_template_block WHERE targettplname IN (".dimplode($tpls).")");
			while(($value=DB::fetch($query))) {
				if(!isset($pageblocks[$value['targettplname']])) {
					$pageblocks[$value['targettplname']] = array();
				}
				$pageblocks[$value['targettplname']][] = intval($value['bid']);
				$bids[] = intval($value['bid']);
			}
		}
		$pageblocks['others'] = array();
		if(!$_G['group']['allowdiy']) {
			$query = DB::query("SELECT bid FROM #__common_block_permission WHERE uid='$_G[uid]' AND allowmanage='1'");
			while(($value=DB::fetch($query))) {
				$bids[] = intval($value['bid']);
				$pageblocks['others'][] = intval($value['bid']);
			}
		}
		$bids = array_unique($bids);

		$diytemplate = array();
		foreach((array)$pageblocks as $key=>$value) {
			if(isset($_G['cache']['diytemplatename'][$key])) {
				$diytemplate[$key] = $_G['cache']['diytemplatename'][$key];
			} elseif($key == 'others') {
				$diytemplate[$key] = lang('diy', 'None DIY block');
			} else {
				$diytemplate[$key] = $key;
			}
		}

		if($op == 'recommend') {

			$blockclass = '';
			switch ($_GET['idtype']) {
				case 'aid' :
					$blockclass = 'portal_article';
					break;
			}

			if($bids) {
				$query = DB::query("SELECT bid, `name` FROM #__common_block WHERE bid IN (".dimplode($bids).") AND blockclass='$blockclass'");
				while(($value=DB::fetch($query))) {
					$blocks[$value['bid']] = !empty($value['name']) ? $value['name'] : '#'.$value['bid'];
				}
			}

		} elseif($op == 'search') {

			if(!empty($bids)) {
				$wherearr = array();
				$wherearr[] = "b.bid IN (".dimplode($bids).')';
				if($_GET['searchkey']) {
					$_GET['searchkey'] = trim($_GET['searchkey']);
					if (preg_match('/^[#]?(\d+)$/', $_GET['searchkey'],$match)) {
						$bid = intval($match[1]);
						$wherearr = array(" b.bid='$bid'");
					} else {
						$_GET['searchkey'] = stripsearchkey($_GET['searchkey']);
						$wherearr[] = " b.name LIKE '%$_GET[searchkey]%'";
					}
				}

				require_once libfile('function/block');
				$wheresql = implode(' AND ',$wherearr);
				$query = DB::query("SELECT b.bid, b.`name`, b.blockclass, b.script, tb.targettplname FROM #__common_block b LEFT JOIN #__common_template_block tb ON b.bid=tb.bid WHERE $wheresql LIMIT 100");
				while(($value=DB::fetch($query))) {
					$value['name'] = empty($value['name']) ? '#'.$value['bid'] : $value['name'];
					$theclass = block_getclass($value['blockclass']);
					$value['blockclassname'] = $theclass['name'];
					$value['datasrc'] = $theclass['script'][$value['script']];
					$diyurl = block_getdiyurl($value['targettplname']);
					$value['diyurl'] = $diyurl['url'];
					$value['tplname'] = $diytemplate[$value['targettplname']];
					$value['isrecommendable'] = block_isrecommendable($value);
					$blocks[$value['bid']] = $value;
				}
			}

		} else {

			$theurl = 'index.php?option=block&task=portalblock';
			$perpage = 5;
			$page = max(1,intval($_GET['page']));
			$start = ($page-1)*$perpage;
			if($start<0) $start = 0;
			$end = $start + $perpage;
			$multi = multi(count($pageblocks), $perpage, $page, $theurl);
			$allpageblocks = $pageblocks;
			$bids = $pageblocks = $diyurls = array();
			$cursor = 0;
			require_once libfile('function/block');
			foreach((array)$allpageblocks as $key=>$value) {
				if($cursor >= $start && $cursor < $end) {
					$pageblocks[$key] = $value;
					$bids = array_merge($bids, $value);
					$diyurl = block_getdiyurl($key);
					$diyurls[$key] = $diyurl['url'];
				} elseif($cursor >= $end) {
					break;
				}
				$cursor++;
			}

			if($bids) {
				$query = DB::query("SELECT bid, `name`, blockclass FROM #__common_block WHERE bid IN (".dimplode($bids).")");
				while(($value=DB::fetch($query))) {
					$value['isrecommendable'] = block_isrecommendable($value);
					$value['name'] = !empty($value['name']) ? $value['name'] : '#'.$value['bid'];
					$blocks[$value['bid']] = $value;
				}
			}
		}

		include_once template("block/portalblock");
	}
	function onBlockData(){
		global $modsession;
		global $_G, $category, $navtitle;
		$op = in_array($_GET['op'], array('verify')) ? $_GET['op'] : 'verify';
		if(!checkperm('allowdiy') && !checkperm('allowauthorizedblock')) {
			showmessage('You do not have permission to use the portal management', dreferer());
		}
		loadcache('diytemplatename');
		$blocks = $bids = $tpls = array();
		$diytemplate = array();
		if(checkperm('allowdiy')) {
			$tpls = array_keys($_G['cache']['diytemplatename']);
		} else {
			$tpls = array();
		}
		if($tpls) {
			$query = DB::query("SELECT bid FROM #__common_template_block WHERE targettplname IN (".dimplode($tpls).")");
			while(($value=DB::fetch($query))) {
				$bids[] = intval($value['bid']);
			}
		}
		if(!$_G['group']['allowdiy']) {
			$query = DB::query("SELECT bid FROM #__common_block_permission WHERE uid='$_G[uid]' AND allowmanage='1'");
			while(($value=DB::fetch($query))) {
				$bids[] = intval($value['bid']);
			}
		}
		$bids = array_unique($bids);
		if(submitcheck('batchsubmit')) {
			$tourl = dreferer();
			if(!in_array($_POST['optype'], array('pass', 'delete'))) {
				showmessage('Pls select a option', $tourl);
			}
			$ids = array();
			if($_POST['ids']) {
				$query = DB::query("SELECT dataid, bid FROM #__common_block_item_data WHERE dataid IN (".dimplode($_POST['ids']).')');
				while(($value=DB::fetch($query))) {
					if(in_array($value['bid'], $bids)) {
						$ids[] = intval($value['dataid']);
					}
				}
			}
			if(empty($ids)) {
				showmessage('Please select at least one audit data', $tourl);
			}
			if($_POST['optype']=='pass') {
				DB::query("UPDATE #__common_block_item_data SET isverified='1', verifiedtime='$_G[timestamp]' WHERE dataid IN (".dimplode($ids).")");
			} elseif($_POST['optype']=='delete') {
				DB::query("DELETE FROM #__common_block_item_data WHERE dataid IN (".dimplode($ids).")");
			}
			showmessage('Operation done!', $tourl);
		}
		$theurl = 'index.php?option=block&task=blockdata';
		$perpage = 20;
		$page = max(1,intval($_GET['page']));
		$start = ($page-1)*$perpage;
		if($start<0) $start = 0;
		if($_GET['searchkey']) {
			$_GET['searchkey'] = trim($_GET['searchkey']);
			if (preg_match('/^[#]?(\d+)$/', $_GET['searchkey'],$match)) {
				$bid = intval($match[1]);
				$bids = in_array($bid, $bids) ? array($bid) : array();
			} elseif($bids) {
				$_GET['searchkey'] = stripsearchkey($_GET['searchkey']);
				$query = DB::query("SELECT bid FROM #__common_block WHERE bid IN (".dimplode($bids).") AND name LIKE '%$_GET[searchkey]%'");
				$bids = array();
				while(($value=DB::fetch($query))) {
					$bids[] = intval($value['bid']);
				}
			}
		}
		$datalist = $ids = array();
		$multi = '';
		if($bids) {
			$count = DB::result_first("SELECT COUNT(*) FROM #__common_block_item_data WHERE bid IN (".dimplode($bids).") AND isverified='0'");
			if($count) {
				$query = DB::query("SELECT * FROM #__common_block_item_data WHERE bid IN (".dimplode($bids).") AND isverified='0' LIMIT $start, $perpage");
				while(($value=DB::fetch($query))) {
					$datalist[] = $value;
					$ids[] = $value['bid'];
				}
				$multi = multi($count, $perpage, $page, $theurl);
			}
		}
		if($ids) {
			include_once libfile('function/block');
			$ids = array_unique($ids);
			$query = DB::query("SELECT b.bid, b.name as blockname, tb.targettplname FROM #__common_block b LEFT JOIN #__common_template_block tb ON b.bid=tb.bid WHERE b.bid IN (".dimplode($ids).")");
			while(($value=DB::fetch($query))) {
				$diyurl = block_getdiyurl($value['targettplname']);
				$value['diyurl'] = $diyurl['url'];
				$value['tplname'] = isset($_G['cache']['diytemplatename'][$value['targettplname']]) ? $_G['cache']['diytemplatename'][$value['targettplname']] : $value['targettplname'];
				$blocks[$value['bid']] = $value;
			}
		}
		include_once template("block/blockdata");
	}

}
